<template>
  <div class="error-handling-test">
    <n-card title="错误处理逻辑测试" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <n-space vertical size="large">
        <!-- 说明 -->
        <n-card title="测试说明" size="small">
          <n-alert type="info" :show-icon="false">
            <p class="mb-8px">此页面用于测试API错误响应的处理逻辑，验证错误信息的正确提取和显示。</p>
            <p><strong>API错误响应结构：</strong></p>
            <n-code language="json" :code="apiErrorStructure" />
          </n-alert>
        </n-card>

        <!-- 测试按钮 -->
        <n-card title="错误处理测试" size="small">
          <n-space vertical>
            <n-space>
              <n-button type="error" @click="testError400">
                测试400错误
              </n-button>
              <n-button type="error" @click="testError401">
                测试401错误
              </n-button>
              <n-button type="error" @click="testError403">
                测试403错误
              </n-button>
              <n-button type="error" @click="testError404">
                测试404错误
              </n-button>
              <n-button type="error" @click="testError500">
                测试500错误
              </n-button>
            </n-space>
            <n-space>
              <n-button type="warning" @click="testNetworkError">
                测试网络错误
              </n-button>
              <n-button type="warning" @click="testCustomError">
                测试自定义错误
              </n-button>
            </n-space>
          </n-space>
        </n-card>

        <!-- 测试结果 -->
        <n-card title="测试结果" size="small" v-if="testResults.length > 0">
          <n-timeline>
            <n-timeline-item
              v-for="(result, index) in testResults"
              :key="index"
              :type="result.type"
              :title="result.title"
              :content="result.content"
              :time="result.time"
            />
          </n-timeline>
        </n-card>

        <!-- 错误处理函数代码 -->
        <n-card title="错误处理函数" size="small">
          <n-code language="javascript" :code="errorHandlingCode" />
        </n-card>
      </n-space>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useMessage } from 'naive-ui'

const message = useMessage()

// 测试结果
const testResults = ref([])

// API错误结构示例
const apiErrorStructure = `{
  "code": 400,
  "message": "该领域下还有专家，无法删除",
  "data": {
    "error": {
      "statusCode": 400,
      "code": null,
      "isOperational": true,
      "message": "该领域下还有专家，无法删除"
    }
  }
}`

// 错误处理函数代码
const errorHandlingCode = `// 根据API返回的错误结构提取错误信息
if (error?.response?.data) {
  const responseData = error.response.data
  
  // 优先使用API返回的message字段
  if (responseData.message) {
    errorMessage = responseData.message
  } 
  // 如果没有message，尝试从data.error.message获取
  else if (responseData.data?.error?.message) {
    errorMessage = responseData.data.error.message
  }
  // 根据状态码提供默认错误信息
  else if (error?.response?.status === 400) {
    errorMessage = '请求参数错误'
  } else if (error?.response?.status === 401) {
    errorMessage = '权限不足，请重新登录'
  } else if (error?.response?.status === 403) {
    errorMessage = '没有删除权限'
  } else if (error?.response?.status === 404) {
    errorMessage = '要删除的数据不存在'
  } else if (error?.response?.status >= 500) {
    errorMessage = '服务器错误，请稍后重试'
  }
} 
// 如果没有response.data，尝试从error.message获取
else if (error?.message) {
  errorMessage = error.message
}`

// 错误处理函数
const handleError = (error: any) => {
  let errorMessage = '删除失败，请重试'
  
  // 根据API返回的错误结构提取错误信息
  if (error?.response?.data) {
    const responseData = error.response.data
    
    // 优先使用API返回的message字段
    if (responseData.message) {
      errorMessage = responseData.message
    } 
    // 如果没有message，尝试从data.error.message获取
    else if (responseData.data?.error?.message) {
      errorMessage = responseData.data.error.message
    }
    // 根据状态码提供默认错误信息
    else if (error?.response?.status === 400) {
      errorMessage = '请求参数错误'
    } else if (error?.response?.status === 401) {
      errorMessage = '权限不足，请重新登录'
    } else if (error?.response?.status === 403) {
      errorMessage = '没有删除权限'
    } else if (error?.response?.status === 404) {
      errorMessage = '要删除的数据不存在'
    } else if (error?.response?.status >= 500) {
      errorMessage = '服务器错误，请稍后重试'
    }
  } 
  // 如果没有response.data，尝试从error.message获取
  else if (error?.message) {
    errorMessage = error.message
  }
  
  return errorMessage
}

// 记录测试结果
const logTestResult = (title: string, originalError: any, extractedMessage: string) => {
  testResults.value.unshift({
    type: 'error',
    title: title,
    content: `原始错误: ${JSON.stringify(originalError, null, 2)}\n提取的错误信息: ${extractedMessage}`,
    time: new Date().toLocaleTimeString()
  })
}

// 测试400错误
const testError400 = () => {
  const mockError = {
    response: {
      status: 400,
      data: {
        code: 400,
        message: "该领域下还有专家，无法删除",
        data: {
          error: {
            statusCode: 400,
            code: null,
            isOperational: true,
            message: "该领域下还有专家，无法删除"
          }
        }
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('400错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试401错误
const testError401 = () => {
  const mockError = {
    response: {
      status: 401,
      data: {
        code: 401,
        message: "未授权访问",
        data: null
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('401错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试403错误
const testError403 = () => {
  const mockError = {
    response: {
      status: 403,
      data: {
        code: 403,
        message: "权限不足",
        data: null
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('403错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试404错误
const testError404 = () => {
  const mockError = {
    response: {
      status: 404,
      data: {
        code: 404,
        message: "资源不存在",
        data: null
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('404错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试500错误
const testError500 = () => {
  const mockError = {
    response: {
      status: 500,
      data: {
        code: 500,
        message: "服务器内部错误",
        data: null
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('500错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试网络错误
const testNetworkError = () => {
  const mockError = {
    message: "Network Error",
    code: "NETWORK_ERROR"
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('网络错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}

// 测试自定义错误
const testCustomError = () => {
  const mockError = {
    response: {
      status: 400,
      data: {
        code: 400,
        message: "", // 空message
        data: {
          error: {
            statusCode: 400,
            message: "从data.error.message获取的错误信息"
          }
        }
      }
    }
  }
  
  const extractedMessage = handleError(mockError)
  logTestResult('自定义错误测试', mockError, extractedMessage)
  message.error(extractedMessage)
}
</script>

<style scoped>
.error-handling-test {
  padding: 20px;
}
</style>
